<?php

namespace addons\yunfood\model;

use addons\yunfood\library\ModelTrait;
use app\admin\model\yunfood\FundUser;
use app\common\model\User;
use think\Db;
use think\Exception;
use think\exception\PDOException;
use think\Log;
use think\Model;
use traits\model\SoftDelete;

/**
 * 订单退款模型
 */
class OrderRefund extends Model
{
    use ModelTrait;
    use SoftDelete;

    // 表名,不含前缀
    protected $name = 'yunfood_order_refund';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = true;

    // 定义时间戳字段名
    protected $deleteTime = 'deleted_at';
    protected $updateTime = 'updated_at';
    protected $createTime = 'created_at';

    // 不显示的字段
    protected $hidden = ['deleted_at'];

    protected $resultSetType = 'collection';

    // 用户数据
    public function userData()
    {
        return $this->hasOne(User::class, 'id', 'user_id');
    }

    // 订单数据
    public function orderData()
    {
        return $this->hasOne(Order::class, 'order_no', 'order_no');
    }

    // 订单商品数据
    public function orderItemData()
    {
        return $this->hasOne(OrderItem::class, 'order_item_no', 'order_item_no');
    }

    // 类别
    const TYPE_ORDER      = 'order';
    const TYPE_ORDER_ITEM = 'order_item';

    public static function getTypeList()
    {
        return [self::TYPE_ORDER => __('整个订单'), self::TYPE_ORDER_ITEM => __('部分商品')];
    }

    public function getTypeTextAttr($value, $data)
    {
        $optionList = self::getTypeList();

        return $optionList[$data['type']] ?? $data['type'];
    }

    // 退款原因
    const REASON_CHAT  = 'chat';
    const REASON_OTHER = 'other';

    public static function getReasonList()
    {
        return [self::REASON_CHAT => __('沟通协商'), self::REASON_OTHER => __('其他')];
    }

    public function getReasonTextAttr($value, $data)
    {
        $optionList = self::getReasonList();

        return $optionList[$data['reason']] ?? $data['reason'];
    }

    // 退款方式
    const REFUND_WAY_ORIGIN  = 'origin';
    const REFUND_WAY_OFFLINE = 'offline';

    public static function getRefundWayList()
    {
        return [
            self::REFUND_WAY_ORIGIN  => __('原路退回'),
            self::REFUND_WAY_OFFLINE => __('线下转账')
        ];
    }

    public function getRefundWayTextAttr($value, $data)
    {
        $optionList = self::getRefundWayList();

        return $optionList[$data['refund_way']] ?? $data['refund_way'];
    }

    // 退款图片列表
    public function getRefundPhotoListAttr($value, $data)
    {
        $photoList = [];
        if ($photos = $data['refund_photos']) {
            $photos = explode(',', $photos);
            foreach ($photos as $item) {
                $photoList[] = ['src' => $item, 'url' => cdnurl($item, true)];
            }
        }

        return $photoList;
    }

    // 退款状态
    const REFUNDMENT_STATUS_NONE = 0;
    const REFUNDMENT_STATUS_WAIT = 1;
    const REFUNDMENT_STATUS_DONE = 2;
    const REFUNDMENT_STATUS_FAIL = 3;

    public static function getRefundmentStatusList()
    {
        return [
            self::REFUNDMENT_STATUS_NONE => __('无'),
            self::REFUNDMENT_STATUS_WAIT => __('待退款'),
            self::REFUNDMENT_STATUS_DONE => __('已退款'),
            self::REFUNDMENT_STATUS_FAIL => __('已失败'),
        ];
    }

    public function getRefundmentStatusTextAttr($value, $data)
    {
        $optionList = self::getRefundmentStatusList();

        return $optionList[$data['refundment_status']] ?? $data['refundment_status'];
    }

    // 状态
    const STATUS_WAIT   = 1;
    const STATUS_DONE   = 2;
    const STATUS_CANCEL = 3;
    const STATUS_REFUSE = 4;
    const STATUS_ING    = 5;
    const STATUS_FAIL   = 6;

    public static function getStatusList()
    {
        return [
            self::STATUS_WAIT   => __('待处理'),
            self::STATUS_DONE   => __('已退款'),
            self::STATUS_CANCEL => __('已取消'),
            self::STATUS_REFUSE => __('已拒绝'),
            self::STATUS_ING    => __('退款中'),
            self::STATUS_FAIL   => __('退款失败')
        ];
    }

    public function getStatusTextAttr($value, $data)
    {
        $optionList = self::getStatusList();

        return $optionList[$data['status']] ?? $data['status'];
    }

    public static function finishRefund($refundNo, $refundmentStatus)
    {
        Db::startTrans();
        try {
            $orderRefund = OrderRefund::where(['refund_no' => $refundNo])->lock(true)->find();
            if ($orderRefund) {
                $orderRefund->refundment_status = $refundmentStatus;
                $orderRefund->status = $refundmentStatus == self::REFUNDMENT_STATUS_DONE ? OrderRefund::STATUS_DONE : OrderRefund::STATUS_FAIL;
                $orderRefund->save();

                // 处理订单
                self::handleOrderRefund($orderRefund);
            }
            Db::commit();
        } catch (PDOException | Exception $e) {
            Db::rollback();
            Log::write('失败原因', $e->getMessage());
            throw $e;
        }
    }

    public static function handleOrderRefund($orderRefund, $checkAmount = false)
    {
        // 主订单
        if (! $orderData = $orderRefund->orderData) {
            throw new Exception('订单不存在');
        }

        // 子订单
        $orderItemData = null;
        if ($orderRefund->order_item_no) {
            if (! $orderItemData = $orderRefund->orderItemData) {
                throw new Exception('订单商品不存在');
            }
        }

        // 检查金额
        if ($checkAmount) {
            $balanceRel = $orderItemData ? $orderItemData->balance : $orderData->balance;
            if ($orderRefund->refund_balance_rel > $balanceRel) {
                throw new Exception('实际退回余额不能大于订单余额支付');
            }
            $paymentRel = $orderItemData ? $orderItemData->payment_rel : $orderData->payment_rel;
            if ($orderRefund->refund_amount_rel > $paymentRel) {
                throw new Exception('实际退回现金不能大于订单现金支付');
            }
        }

        // 发起退款
        if ($orderRefund->refundment_status == OrderRefund::REFUNDMENT_STATUS_WAIT) {
            // 原路退回，退回成功后再处理余额退款
            $refundmentData = Refundment::submitRefund($orderRefund, $orderData->payment_no);
            $orderRefund->refundment_no = $refundmentData->refundment_no;
            $orderRefund->save();
            return;
        }
        if ($orderItemData) {
            if ($orderRefund->status == OrderRefund::STATUS_DONE) {
                $orderItemRefundStatus = OrderItem::REFUND_STATUS_DONE;
            } elseif ($orderRefund->status == OrderRefund::STATUS_REFUSE) {
                $orderItemRefundStatus = OrderItem::REFUND_STATUS_REFUSE;
            } elseif ($orderRefund->status == OrderRefund::STATUS_FAIL) {
                $orderItemRefundStatus = OrderItem::REFUND_STATUS_FAIL;
            } else {
                throw new Exception('当前状态不支持后续操作');
            }
            $orderItemData->refund_status = $orderItemRefundStatus;
            $orderItemData->save();

            if ($orderItemRefundStatus == OrderItem::REFUND_STATUS_DONE) {
                $allRefund = true;
                if ($orderItemList = $orderData->orderItemListData) {
                    foreach ($orderItemList as $item) {
                        if ($item->refund_status != OrderItem::REFUND_STATUS_DONE) {
                            $allRefund = false;
                        }
                    }
                }
                // 全部退款完成
                if ($allRefund) {
                    $orderData->refund_status = Order::REFUND_STATUS_DONE;
                    $orderData->status = Order::STATUS_HAS_CLOSE;
                    $orderData->save();
                }
            }
        } else {
            if ($orderRefund->status == OrderRefund::STATUS_DONE) {
                $orderRefundStatus = Order::REFUND_STATUS_DONE;
            } elseif ($orderRefund->status == OrderRefund::STATUS_REFUSE) {
                $orderRefundStatus = Order::REFUND_STATUS_REFUSE;
            } elseif ($orderRefund->status == OrderRefund::STATUS_FAIL) {
                $orderRefundStatus = Order::REFUND_STATUS_FAIL;
            } else {
                throw new Exception('当前状态不支持后续操作');
            }
            $orderData->refund_status = $orderRefundStatus;
            if ($orderRefundStatus == Order::REFUND_STATUS_DONE) {
                $orderData->status = Order::STATUS_HAS_CLOSE;
            }
            $orderData->save();
        }

        // 余额退款
        if ($orderRefund->status == OrderRefund::STATUS_DONE && $orderRefund->refund_balance_rel > 0) {
            FundUser::amountCounter($orderRefund->user_id, FundRecord::ACTION_REFUND, $orderRefund->refund_balance_rel,
                false, FundRecord::SOURCE_TYPE_ORDER_REFUND, $orderRefund->refund_no);
        }
    }
}
